package br.ufrj.dcc.smarthotel.controls;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import br.ufrj.dcc.smarthotel.R;
import br.ufrj.dcc.smarthotel.activities.DashboardActivity;
import br.ufrj.dcc.smarthotel.activities.SmartHotelActivity;
import br.ufrj.dcc.smarthotel.entities.Session;
import br.ufrj.dcc.smarthotel.entities.User;

public class SmartHotelControl extends Control {
	SmartHotelActivity activity;
	
	public SmartHotelControl(SmartHotelActivity activity) {
		this.activity = activity;
	}
	
	public void Login() {
		if (this.isValidUser()) {
			Session session = this.getSession();
			
			Map<String, Object> kvPairs = new HashMap<String, Object>();
			
			kvPairs.put("session", session);
			
			String resultLocation = this.doPost("session", kvPairs);
			
			if (resultLocation != null) {
				this.activity.showQuickMessage(R.string.msg_UserLoginSucceful);
				
				Hashtable<String, String> params = new Hashtable<String, String>();
				
				params.put("sessionLocation", resultLocation);
				
				this.activity.startActivity(DashboardActivity.class, params);
			}
			else {
				this.activity.showQuickMessage(R.string.msg_UserLoginFailed);
			}
		}
	}

	private Session getSession() {
		Session session = new Session();
		User sessionUser = new User();
		
		sessionUser.setEmail(this.activity.getEmail());
		sessionUser.setPassword(this.activity.getPassword());
		
		session.setUser(sessionUser);
		
		return session;
	}

	private boolean isValidUser() {
		boolean valid = true;
		
		if (this.activity.getEmail().length() == 0) {
			this.activity.showQuickMessage(R.string.msg_InvalidEmail);
			valid = false;
		}
		
		if (this.activity.getPassword().length() == 0) {
			this.activity.showQuickMessage(R.string.msg_InvalidPassword);
			valid = false;
		}
		
		return valid;
	}

}
